import { hash } from "ohash";

// 后端返回的数据封装
export interface ResOptions<T> {
  data?: T;
  msg?: string;
  success?: boolean;
  code?: number;
}

/**
 * api请求封装
 * @param { String } url 请求地址
 * @param { Object } options useFetch第二个参数
 * @param { Object } headers 自定义header头, 单独设置headers区分请求参数，也好设置类型
 */
const fetch = async (
  url: string,
  options?: any,
  headers?: any
): Promise<any> => {
  const reqUrl = `http://localhost:5012/api/${url}`;
  const key = hash(JSON.stringify(options) + url);
  const customerHeaders = {
    Accept: "application/json, application/xml, text/plain, text/html, *.*",
    ...headers,
  };

  if (process.client) {
    customerHeaders["Authorization"] = `Bearer ${window.localStorage.getItem(
      "token"
    )}`;
  }

  return await new Promise((resolve, reject) => {
    useFetch(reqUrl, { ...options, key, headers: customerHeaders })
      .then(({ data, error }) => {
        if (error.value) {
          reject(error.value);
          return;
        }
        if (!data.value) {
          throw createError({
            statusCode: 500,
            statusMessage: reqUrl,
            message: "处理错误",
          });
        } else {
          resolve(data.value);
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });
};

/**
 * 导出常用的get、post、put、delete方法
 * **/
export default class Http {
  get(url: string, params?: any, headers?: any): Promise<any> {
    return fetch(url, { method: "get", params }, headers);
  }

  post(url: string, params?: any, headers?: any): Promise<any> {
    return fetch(url, { method: "post", body: params }, headers);
  }

  put(url: string, params?: any, headers?: any): Promise<any> {
    return fetch(url, { method: "put", body: params }, headers);
  }

  delete(url: string, params?: any, headers?: any): Promise<any> {
    return fetch(url, { method: "delete", body: params }, headers);
  }
}
